package Controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.XMLFormatter;

public class LogManager {
    
    public static void logEvent(String loggerName, Level level, String message, String ipAdd, String username)
    {
        Object[] params = new Object[2];
        
        try
        {
              FileHandler logFile = new FileHandler("%h/NetBeansProjects/foobar.log", true);
              //FileHandler logFile = new FileHandler("%h/foobar.log", true);
              Logger log = Logger.getLogger(loggerName);
              //logFile.setFormatter(new SimpleFormatter());
              //logFile.setFormatter(new XMLFormatter());
              logFile.setFormatter(getCustomFormatter());
              logFile.setEncoding("UTF-8");
              
              log.addHandler(logFile);
              
              params[0] = ipAdd;
              params[1] = username;

              log.log(level, message, params);

              logFile.close();
        }
        catch(IOException e){
            System.out.println("Unable to initialize log file!");
        }        
    }
    
    private static Formatter getCustomFormatter()
    {
        return new Formatter()
        {
            @Override
            public String format(LogRecord record)
            {
		Object[] arguments = new Object[6];
		arguments[0] = new Timestamp(record.getMillis());
		arguments[1] = record.getLoggerName();
		arguments[2] = record.getLevel();
                arguments[3] = record.getParameters()[0];
                arguments[4] = record.getParameters()[1];
		arguments[5] = record.getMessage();
		return new MessageFormat("{0,time,yyyy-MM-dd hh:mm:ss} [ {1} | {2} | {3} | {4} ]: {5}" + System.getProperty("line.separator")).format(arguments);
            }	
        };
    }
}
